package com.lucky.carcodepro.common;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjUtil;
import lombok.AccessLevel;
import lombok.Data;
import lombok.experimental.FieldDefaults;

import java.time.LocalDateTime;

/**
 * SimpleSharding
 * <p>
 * 描述：分表组件
 *
 * @author Annie
 * @version 2024/10/2 16:16
 */

public class SimpleSharding
{
    /* 分表开始月 */
    private static final String SHARDING_MONTH = "202410";
    private static final InheritableThreadLocal<SimpleShardingBound> month = new InheritableThreadLocal<>();

    /**
     * 开启分表参数
     *
     * @param shardingMonth 月份
     * @param ifClear       是否由框架代为重置月份
     */
    public static void sharding(String shardingMonth, Boolean ifClear)
    {
        SimpleShardingBound simpleShardingBound = month.get();
        if (ObjUtil.isNotNull(simpleShardingBound))
        {
            simpleShardingBound.month = shardingMonth;
        } else
        {
            month.set(new SimpleShardingBound(
                    shardingMonth, null, ifClear
            ));
        }
    }

    public static void sharding(String shardingMonth)
    {
        sharding(shardingMonth, false);
    }

    public static void sharding(LocalDateTime ldt)
    {
        sharding(LocalDateTimeUtil.format(ldt, DatePattern.SIMPLE_MONTH_PATTERN), false);
    }

    public static void sharding(SimpleShardingBound shardingBound)
    {
        month.set(shardingBound);
    }

    public static void clear()
    {
        month.remove();
    }

    public static SimpleShardingBound get()
    {
        return month.get();
    }

    @Data
    @FieldDefaults(level = AccessLevel.PRIVATE)
    public static class SimpleShardingBound
    {
        /* 月份 */
        String month;
        /* 表名 */
        String tableName;
        /* 是否需要拦截器清理缓存 */
        Boolean needClear = false;

        public SimpleShardingBound(String month, String tableName)
        {
            this(month, tableName, false);
        }

        public SimpleShardingBound(String month, String tableName, Boolean needClear)
        {
            // 分表月份大于起点月份，则强制重置为起点月份
            this.month = month.compareTo(SHARDING_MONTH) >= 0 ? month : SHARDING_MONTH;
            this.tableName = tableName;
            this.needClear = needClear;
        }

        public String getShardingTableName()
        {
            return tableName + "-" + month;
        }
    }
}
